package com.cloudxingkong.dianyinke.Student.Ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Adapter.SelectCurriculaAdapter;
import com.cloudxingkong.dianyinke.Student.bean.MyAppointmentEntity;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 约课Activity
 */
public class SelectCurricula extends BaseActivity implements SelectCurriculaAdapter.onTouchPosition, SwipeRefreshLayout.OnRefreshListener {

    private SelectCurriculaAdapter curriculaAdapter;
    private List<MyAppointmentEntity.ListBean> list;
    private ListView lv_selectCurricula;
    private SharedPreferences sharedPreferences;
    private int orderID;
    private String teacherID;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setContentView(R.layout.activity_select_curricula);
        init();
        loadData();
        lv_selectCurricula.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(SelectCurricula.this, ConfirmOrder.class);
                intent.putExtra("title", list.get(position).getTitle() + "");
                intent.putExtra("content", list.get(position).getNote() + "");
                intent.putExtra("price", list.get(position).getPrice() + "");
                intent.putExtra("teacherPic", list.get(position).getAvatar());
                int teacherid = list.get(position).getTeacherid();
                int lessonid = list.get(position).getLessonid();
                intent.putExtra("teacherID", teacherid + "");
                intent.putExtra("lessonID", lessonid + "");
                Log.e("test", "teacherid&lessonid " + teacherid + " - " + lessonid);
                startActivity(intent);
            }
        });
    }

    private void loadData() {
        swipeRefreshLayout.setRefreshing(true);
        final String sessionid = CookieHelper.getSessionID(sharedPreferences);
        final String upLoadUrl = ThisUri.SERVER_YUMING + StudentUri.MYAPPOINTMENT;
        RequestParams params = new RequestParams(upLoadUrl);
        params.addHeader("cookie", sessionid);
        params.addBodyParameter("teacherid", teacherID + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "约课" + result);
                Message message = handler.obtainMessage();
                message.what = 1;
                message.obj = result;
                handler.sendMessage(message);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                handler.sendEmptyMessage(2);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void init() {
        sharedPreferences = SelectCurricula.this.getSharedPreferences("data_dyk", 0);
        Intent intent = getIntent();
        teacherID = intent.getStringExtra("teacherID");
        list = new ArrayList<>();
        lv_selectCurricula = ((ListView) findViewById(R.id.lv_selectCurricula));
        curriculaAdapter = new SelectCurriculaAdapter(list, this, this);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.selectCurricula_swipeRefresh);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(this);
        //设置自动刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String state = (String) msg.obj;
                    if (state != null) {
                        Gson gson = new Gson();
                        MyAppointmentEntity myAppointmentEntity = gson.fromJson(state, MyAppointmentEntity.class);
                        list.addAll(myAppointmentEntity.getList());
                        lv_selectCurricula.setAdapter(curriculaAdapter);
                        swipeRefreshLayout.setRefreshing(false);
                        curriculaAdapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(getApplication(), "约课内容出现错误", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 2:
                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(getApplication(), "加载错误，请重新加载", Toast.LENGTH_SHORT).show();
            }
        }
    };

    //返回按钮
    public void back(View view) {
        finish();
    }

    //接口
    public void onTouch(int position) {
        orderID = list.get(position).getId();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("orderID", orderID + "");
        editor.commit();
    }

    @Override
    public void onRefresh() {
        list.clear();
        loadData();
    }
}
